<template>
  <div class="book-detail-container">
    <div class="book-detail-content">
      <!-- 图书基本信息 -->
      <div class="book-info-section">
        <div class="book-cover">
          <el-image
            :src="book.coverImage || '/default-book.jpg'"
            fit="cover"
            class="cover-image"
          />
        </div>
        <div class="book-details">
          <h1 class="book-title">{{ book.title }}</h1>
          <div class="book-meta">
            <p><strong>作者：</strong>{{ book.author }}</p>
            <p><strong>出版社：</strong>{{ book.publisher }}</p>
            <p><strong>出版日期：</strong>{{ formatDate(book.publishDate) }}</p>
            <p><strong>ISBN：</strong>{{ book.isbn }}</p>
            <p><strong>分类：</strong>{{ book.categoryName }}</p>
            <p><strong>页数：</strong>{{ book.pages }}页</p>
            <p><strong>语言：</strong>{{ book.language }}</p>
          </div>
          <div class="book-rating">
            <el-rate
              v-model="book.rating"
              disabled
              show-score
              text-color="#ff9900"
              score-template="{value}分"
            />
            <span class="rating-count">({{ book.ratingCount }}人评价)</span>
          </div>
          <div class="book-status">
            <el-tag 
              :type="book.status === 'AVAILABLE' ? 'success' : 'danger'"
              size="large"
            >
              {{ book.status === 'AVAILABLE' ? '可借阅' : '已借出' }}
            </el-tag>
            <span class="stock-info">库存：{{ book.stock }}本</span>
          </div>
          <div class="book-actions">
            <el-button 
              type="primary" 
              size="large" 
              :disabled="book.status !== 'AVAILABLE'"
              @click="borrowBook"
              :loading="borrowing"
            >
              {{ book.status === 'AVAILABLE' ? '立即借阅' : '已借出' }}
            </el-button>
            <el-button 
              size="large" 
              :icon="book.isFavorite ? 'StarFilled' : 'Star'"
              :type="book.isFavorite ? 'danger' : 'default'"
              @click="toggleFavorite"
            >
              {{ book.isFavorite ? '已收藏' : '收藏' }}
            </el-button>
            <el-button size="large" icon="Share" @click="shareBook">分享</el-button>
          </div>
        </div>
      </div>

      <!-- 图书描述 -->
      <div class="book-description">
        <el-card>
          <template #header>
            <span>图书简介</span>
          </template>
          <div class="description-content">
            <p>{{ book.description || '暂无图书简介' }}</p>
          </div>
        </el-card>
      </div>

      <!-- 目录信息 -->
      <div class="book-catalog" v-if="book.catalog">
        <el-card>
          <template #header>
            <span>目录</span>
          </template>
          <div class="catalog-content">
            <pre>{{ book.catalog }}</pre>
          </div>
        </el-card>
      </div>

      <!-- 相关推荐 -->
      <div class="related-books">
        <el-card>
          <template #header>
            <span>相关推荐</span>
          </template>
          <div class="related-books-grid">
            <div 
              v-for="relatedBook in relatedBooks"
              :key="relatedBook.id"
              class="related-book-item"
              @click="goToBook(relatedBook.id)"
            >
              <el-image
                :src="relatedBook.coverImage || '/default-book.jpg'"
                fit="cover"
                class="related-cover"
              />
              <div class="related-info">
                <h4>{{ relatedBook.title }}</h4>
                <p>{{ relatedBook.author }}</p>
                <el-rate
                  v-model="relatedBook.rating"
                  disabled
                  size="small"
                />
              </div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 评论区 -->
      <div class="book-comments">
        <el-card>
          <template #header>
            <div class="comments-header">
              <span>读者评价 ({{ comments.length }})</span>
              <el-button type="primary" @click="showCommentDialog = true">写评价</el-button>
            </div>
          </template>
          <div class="comments-list">
            <div 
              v-for="comment in comments"
              :key="comment.id"
              class="comment-item"
            >
              <div class="comment-user">
                <el-avatar :src="comment.userAvatar" :size="40" />
                <div class="user-info">
                  <div class="username">{{ comment.username }}</div>
                  <div class="comment-time">{{ formatTime(comment.createTime) }}</div>
                </div>
                <el-rate
                  v-model="comment.rating"
                  disabled
                  size="small"
                />
              </div>
              <div class="comment-content">
                {{ comment.content }}
              </div>
            </div>
          </div>
          <div v-if="comments.length === 0" class="no-comments">
            暂无评价，快来写下第一个评价吧！
          </div>
        </el-card>
      </div>
    </div>

    <!-- 评价对话框 -->
    <el-dialog
      v-model="showCommentDialog"
      title="写评价"
      width="500px"
    >
      <el-form :model="commentForm" label-width="80px">
        <el-form-item label="评分">
          <el-rate v-model="commentForm.rating" />
        </el-form-item>
        <el-form-item label="评价内容">
          <el-input
            v-model="commentForm.content"
            type="textarea"
            :rows="4"
            placeholder="请写下您的读后感..."
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCommentDialog = false">取消</el-button>
        <el-button type="primary" @click="submitComment" :loading="submitting">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getBookDetail, 
  borrowBook as apiBorrowBook,
  favoriteBook,
  unfavoriteBook,
  getRelatedBooks,
  getBookComments,
  addBookComment
} from '@/api/library'

const route = useRoute()
const router = useRouter()

// 响应式数据
const book = ref({})
const relatedBooks = ref([])
const comments = ref([])
const borrowing = ref(false)
const showCommentDialog = ref(false)
const submitting = ref(false)

// 评价表单
const commentForm = reactive({
  rating: 5,
  content: ''
})

// 获取图书详情
const loadBookDetail = async () => {
  try {
    const response = await getBookDetail(route.params.id)
    if (response.code === 200) {
      book.value = response.data
      loadRelatedBooks()
      loadComments()
    } else {
      ElMessage.error('获取图书详情失败')
    }
  } catch (error) {
    console.error('获取图书详情失败:', error)
    ElMessage.error('获取图书详情失败')
  }
}

// 获取相关推荐
const loadRelatedBooks = async () => {
  try {
    const response = await getRelatedBooks(book.value.id)
    if (response.code === 200) {
      relatedBooks.value = response.data || []
    }
  } catch (error) {
    console.error('获取相关推荐失败:', error)
  }
}

// 获取评论
const loadComments = async () => {
  try {
    const response = await getBookComments(book.value.id)
    if (response.code === 200) {
      comments.value = response.data || []
    }
  } catch (error) {
    console.error('获取评论失败:', error)
  }
}

// 借阅图书
const borrowBook = async () => {
  try {
    await ElMessageBox.confirm(`确认要借阅《${book.value.title}》吗？`, '确认借阅', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })
    
    borrowing.value = true
    await apiBorrowBook(book.value.id)
    ElMessage.success('借阅成功')
    book.value.status = 'BORROWED'
    book.value.stock--
  } catch (error) {
    if (error !== 'cancel') {
      console.error('借阅失败:', error)
      ElMessage.error('借阅失败')
    }
  } finally {
    borrowing.value = false
  }
}

// 切换收藏
const toggleFavorite = async () => {
  try {
    if (book.value.isFavorite) {
      await unfavoriteBook(book.value.id)
      book.value.isFavorite = false
      ElMessage.success('已取消收藏')
    } else {
      await favoriteBook(book.value.id)
      book.value.isFavorite = true
      ElMessage.success('已添加收藏')
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 分享图书
const shareBook = () => {
  const url = window.location.href
  navigator.clipboard.writeText(url).then(() => {
    ElMessage.success('链接已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败')
  })
}

// 跳转到其他图书
const goToBook = (bookId) => {
  router.push(`/library/book/${bookId}`)
}

// 提交评价
const submitComment = async () => {
  if (!commentForm.content.trim()) {
    ElMessage.warning('请填写评价内容')
    return
  }
  
  try {
    submitting.value = true
    await addBookComment({
      bookId: book.value.id,
      rating: commentForm.rating,
      content: commentForm.content
    })
    ElMessage.success('评价提交成功')
    showCommentDialog.value = false
    commentForm.rating = 5
    commentForm.content = ''
    loadComments()
  } catch (error) {
    console.error('提交评价失败:', error)
    ElMessage.error('提交评价失败')
  } finally {
    submitting.value = false
  }
}

// 工具函数
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString()
}

const formatTime = (time) => {
  if (!time) return ''
  return new Date(time).toLocaleString()
}

// 页面加载
onMounted(() => {
  loadBookDetail()
})
</script>

<style lang="scss" scoped>
.book-detail-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
}

.book-detail-content {
  max-width: 1200px;
  margin: 0 auto;
}

.book-info-section {
  display: flex;
  gap: 30px;
  background: white;
  padding: 30px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  
  .book-cover {
    flex-shrink: 0;
    
    .cover-image {
      width: 200px;
      height: 280px;
      border-radius: 8px;
    }
  }
  
  .book-details {
    flex: 1;
    
    .book-title {
      font-size: 28px;
      font-weight: 600;
      margin: 0 0 20px 0;
      color: #303133;
    }
    
    .book-meta {
      margin-bottom: 20px;
      
      p {
        margin: 8px 0;
        color: #606266;
        font-size: 14px;
        
        strong {
          color: #303133;
          margin-right: 8px;
        }
      }
    }
    
    .book-rating {
      display: flex;
      align-items: center;
      gap: 10px;
      margin-bottom: 20px;
      
      .rating-count {
        color: #909399;
        font-size: 14px;
      }
    }
    
    .book-status {
      display: flex;
      align-items: center;
      gap: 15px;
      margin-bottom: 30px;
      
      .stock-info {
        color: #606266;
        font-size: 14px;
      }
    }
    
    .book-actions {
      display: flex;
      gap: 12px;
    }
  }
}

.book-description,
.book-catalog,
.related-books,
.book-comments {
  margin-bottom: 20px;
  
  .description-content,
  .catalog-content {
    line-height: 1.6;
    color: #606266;
    
    pre {
      white-space: pre-wrap;
      font-family: inherit;
    }
  }
}

.related-books-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
  
  .related-book-item {
    display: flex;
    flex-direction: column;
    cursor: pointer;
    transition: transform 0.3s;
    
    &:hover {
      transform: translateY(-2px);
    }
    
    .related-cover {
      width: 100%;
      height: 120px;
      border-radius: 4px;
      margin-bottom: 8px;
    }
    
    .related-info {
      h4 {
        margin: 0 0 4px 0;
        font-size: 14px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      
      p {
        margin: 0 0 8px 0;
        color: #909399;
        font-size: 12px;
      }
    }
  }
}

.comments-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.comments-list {
  .comment-item {
    padding: 16px 0;
    border-bottom: 1px solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .comment-user {
      display: flex;
      align-items: center;
      gap: 12px;
      margin-bottom: 8px;
      
      .user-info {
        flex: 1;
        
        .username {
          font-weight: 500;
          color: #303133;
        }
        
        .comment-time {
          font-size: 12px;
          color: #909399;
        }
      }
    }
    
    .comment-content {
      color: #606266;
      line-height: 1.5;
    }
  }
}

.no-comments {
  text-align: center;
  color: #909399;
  padding: 40px 0;
}

@media (max-width: 768px) {
  .book-detail-container {
    padding: 10px;
  }
  
  .book-info-section {
    flex-direction: column;
    padding: 20px;
    
    .book-cover .cover-image {
      width: 150px;
      height: 210px;
    }
    
    .book-details .book-title {
      font-size: 24px;
    }
    
    .book-actions {
      flex-direction: column;
    }
  }
  
  .related-books-grid {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  }
}
</style>
